package com.tutou.ikgroup.websocket.netty;

import cn.hutool.core.bean.BeanUtil;
import com.tutou.ikuser.pojo.po.User;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.tutou.ikuser.util.RedisConstants.LOGIN_TOKEN_KEY;

@ChannelHandler.Sharable
@Component
public class HandlerHttp extends SimpleChannelInboundHandler<HttpHeaders> {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpHeaders httpHeaders) throws Exception {
        //用户获取请求头的token信息来判断用户是否合法
        String authorization = LOGIN_TOKEN_KEY + httpHeaders.get("Authorization");
        Map<Object, Object> userMap = null;
        try {
            userMap = stringRedisTemplate.opsForHash().entries(authorization);
        } catch (Exception e) {
            ctx.writeAndFlush(new TextWebSocketFrame("请登录后重试~"));
            ctx.close();
            return;
        }
        User user = BeanUtil.copyProperties(userMap, User.class);
        //将用户信息传给HandlerWebsocket
        ctx.channel().attr(AttributeKey.valueOf("user")).set(user);
    }
}
